#include <stdio.h>
#include "util.h"
#include "z80.h"
#include "z80_rom.h"

// This file defines the bootloader binary code to be sent to Z80 RAM
// Current: 32KB
#define BOOTSIZE (230)

// CP/M bootloader program
const char Z80_BOOTLOADER_BIN [BOOTSIZE] = {
	0xC3, 0x78, 0x00, 0xDB, 0x3E, 0xE6, 0x02, 0x28, 0xFA, 0x7E, 0x23, 0xD3,
	0x3F, 0x1B, 0x20, 0xF3, 0xC9, 0xDB, 0x3E, 0xE6, 0x02, 0x28, 0xFA, 0x79,
	0xD3, 0x3F, 0xC9, 0x7E, 0xB7, 0xC8, 0xDB, 0x3E, 0xE6, 0x02, 0x28, 0xFA,
	0x7E, 0xD3, 0x3F, 0x23, 0x18, 0xF1, 0xDB, 0x3E, 0xC9, 0xDB, 0x3E, 0xE6,
	0x01, 0x28, 0xFA, 0xDB, 0x3F, 0xC9, 0x42, 0x6F, 0x6F, 0x74, 0x6C, 0x6F,
	0x61, 0x64, 0x65, 0x72, 0x20, 0x76, 0x30, 0x2E, 0x31, 0x20, 0x62, 0x79,
	0x20, 0x62, 0x69, 0x74, 0x72, 0x6F, 0x77, 0x7A, 0x0A, 0x0D, 0x00, 0x4C,
	0x6F, 0x61, 0x64, 0x69, 0x6E, 0x67, 0x20, 0x43, 0x50, 0x2F, 0x4D, 0x2E,
	0x2E, 0x2E, 0x0A, 0x0D, 0x00, 0x44, 0x69, 0x73, 0x6B, 0x20, 0x52, 0x65,
	0x61, 0x64, 0x20, 0x45, 0x72, 0x72, 0x6F, 0x72, 0x21, 0x0A, 0x0D, 0x00,
	0x3E, 0xFF, 0xD3, 0x02, 0x3E, 0x00, 0x32, 0x00, 0x80, 0x21, 0x00, 0xDC,
	0x22, 0x01, 0x80, 0x31, 0xFF, 0xFF, 0x21, 0x36, 0x00, 0xCD, 0x1B, 0x00,
	0x21, 0x53, 0x00, 0xCD, 0x1B, 0x00, 0x3A, 0x00, 0x80, 0x4F, 0xFE, 0x48,
	0xCA, 0xE3, 0x00, 0x3C, 0x32, 0x00, 0x80, 0x79, 0xD3, 0xF2, 0x3E, 0x00,
	0xD3, 0xF3, 0x3E, 0x00, 0xD3, 0xF4, 0x3E, 0xC0, 0xD3, 0xF1, 0xDB, 0xF6,
	0xFE, 0x00, 0xC2, 0xDB, 0x00, 0x21, 0x03, 0x80, 0x11, 0x00, 0x02, 0xDB,
	0xF0, 0x77, 0x23, 0x1B, 0x7B, 0xB2, 0x20, 0xF7, 0x21, 0x03, 0x80, 0xED,
	0x5B, 0x01, 0x80, 0x01, 0x80, 0x00, 0xED, 0xB0, 0xED, 0x53, 0x01, 0x80,
	0xC3, 0x96, 0x00, 0x21, 0x65, 0x00, 0xCD, 0x1B, 0x00, 0x18, 0xFE, 0xC3,
	0x00, 0xF2
};

void ROM_Init()
{   
	*(volatile int*)REG_RESET = 1;
	*(volatile int*)REG_WAIT = 0;
	*(volatile int*)REG_RESET = 0;
    *(volatile int*)REG_BUSREQ = 1;

	// Step 4: MCU 写 SRAM
    uint32_t SRAM_ADDR = 0x0000;
    for (uint32_t i = 0; i < BOOTSIZE; ++i) {
        uint32_t data = ((SRAM_ADDR << 16) & 0xFFFF0000) |
                        ((uint32_t)Z80_BOOTLOADER_BIN[i] & 0xFF);
        *(volatile int*)REG_SRAM = data;
        SRAM_ADDR++;
    }

    *(volatile int*)REG_BUSREQ = 0;
    *(volatile int*)REG_RESET = 1;
	printf("ROM Extracted Success.");
}